
package com.zhu.storesmanager;

import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.models.UserData;
import com.zhu.storesmanager.network.HttpConnectionMethod;
import com.zhu.storesmanager.network.HttpUtil;
import com.zhu.storesmanager.network.RemindSyncData;
import com.zhu.storesmanager.network.NetworkCallback;
import com.zhu.storesmanager.network.ParseNetworkData;
import com.zhu.storesmanager.network.SupervisorData;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.security.DesUtil;
import com.zhu.storesmanager.security.Encoder;
import com.zhu.storesmanager.security.RsaUtil;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DialogUtil;
import com.zhu.storesmanager.utils.PreferenceKeys;
import com.zhu.storesmanager.utils.PreferenceStore;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.SalesData;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 登录界面
 * 
 */
public class UserLoginActivity extends Activity {

    private final static int LOGIN_DIALOG = 0;

    private final static String REMEBER = "1";
    private Handler mHander = new Handler();
    private EditText usernameTxt, passwordTxt, ipText; //用户 密码 IP地址输入    
    private CheckBox mCheckBox = null; //离线登录
    private TextView mClewTextView = null;
    private String[] mProjection = new String[]{ "_id" };
    private RemindSyncData mLoginSyncData = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupViews();
        initLocalData();
    }

    /**
     * 初始化用户名密码
     * 
     */
    private void initLocalData() {
    	int version = PreferenceStore.getInstance(this).getInt(PreferenceKeys.KEY_VERSION, -1);
    	Log.d("zhu", "Preference version="+version);
    	if(version != PreferenceKeys.PREFERENCE_VERSION){
    		PreferenceStore.getInstance(this).putString(PreferenceKeys.KEY_SALESDATA, "");
    		SalesData.getInstance(this).clearAllData(); //清除销量数据
    		PreferenceStore.getInstance(this).putInt(PreferenceKeys.KEY_VERSION, PreferenceKeys.PREFERENCE_VERSION);
    	}
        String username = PreferenceStore.getInstance(this).getString(PreferenceKeys.KEY_USERNAME,
                "");
//        String password = PreferenceStore.getInstance(this).getString(PreferenceKeys.KEY_PASSWORD,
//                "");

        String remeber = PreferenceStore.getInstance(UserLoginActivity.this).getString(PreferenceKeys.KEY_REMEBER, "");
        if(remeber.equals(REMEBER)){
            usernameTxt.setText(username);
//            passwordTxt.setText(password);
        }
    }

    /**
     * 设置显示界面
     * 
     */
    private void setupViews() {
        setContentView(R.layout.activity_user_login);
        usernameTxt = (EditText) this.findViewById(R.id.username_field);
        passwordTxt = (EditText) this.findViewById(R.id.password_field);
        ipText = (EditText) this.findViewById(R.id.id_field);
        mCheckBox = (CheckBox) findViewById(R.id.savepassword);
        mClewTextView = (TextView)findViewById(R.id.clewtext);
        Button submitBtn = (Button) this.findViewById(R.id.login_button);
        submitBtn.setOnClickListener(buttonClickListener);
    }

    /**
     * 点击事件监听
     * 
     */
    private OnClickListener buttonClickListener = new OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.login_button:
                doLogin();
                break;
            default:
                break;
        }
    }
    };

    /**
     * Do Login
     */
    private void doLogin() {
        if (!Actions.isNetwork(this)) { //检查网络
            Actions.alertShowDetails(this, getString(R.string.tips_label),
                    getString(R.string.network_is_unavailable),
                    R.string.dialog_setting, R.string.dialog_close,
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {
                            Actions.openSettingIntent(UserLoginActivity.this,
                                    Settings.ACTION_WIRELESS_SETTINGS);
                        }
                    }, new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {

                        }
                    });

        } else if(!Actions.isGPSWorking(this)){ //检查GPS
            Actions.alertShowDetails(this, getString(R.string.tips_label),
                    getString(R.string.gps_is_unavailable),
                    R.string.dialog_setting, R.string.dialog_close,
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {
                            Actions.openSettingIntent(UserLoginActivity.this,
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        }
                    }, new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {

                        }
                    });
        } else {
            String username = usernameTxt.getText().toString().trim();
            String password = passwordTxt.getText().toString().trim();
            if (username.length() == 0 || password.length() == 0) {
                inputNotCorrect();
            } else {
            	String lastname = PreferenceStore.getInstance(this).getString(PreferenceKeys.KEY_USERNAME, "");
            	if(!lastname.equals(username) && lastname.length() > 0){
            		doLogin(username, password, true);
            	}else{
            		doLogin(username, password, false);
            	}
            }
        }

    }

    /**
     * 输入错误提示
     * 
     */
    private void inputNotCorrect() {
        mHander.post(new Runnable() {
            public void run() {
                DialogUtil.getSimpleDialog(UserLoginActivity.this, "",
                        getString(R.string.username_password_not_empty), null).show();
            }
        });
    }

  

    /**
     * 跳转主界面
     */
    protected void jump2MainActivity() {
        Intent tent = new Intent(UserLoginActivity.this, MainActivity.class);
        UserLoginActivity.this.startActivity(tent);
        UserLoginActivity.this.finish();
    }

    /**
     * 登录进度提示
     */
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case LOGIN_DIALOG:
                ProgressDialog pd = new ProgressDialog(this);
                pd.setMessage(this.getString(R.string.doing_login)
                        + getString(R.string.please_wait));
                pd.setCancelable(false);
                pd.setCanceledOnTouchOutside(false);
                return pd;

            default:
                break;
        }
        return super.onCreateDialog(id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 登录
     * @param name 用户名  
     * @param password 密码
     * @param isNewUser 是否为新用户
     */
    private void doLogin(final String name, final String password, final boolean isNewUser) {
        String text = ipText.getText().toString().trim();
        if(ipText.getVisibility() == View.VISIBLE && text != null && text.length() > 0){ //是否有IP填写
            HttpUtil.HOST = text + "/Sync/";
        }else{
            HttpUtil.HOST = HttpUtil.DEFAULT_HOST;
        }

        boolean isFirst = true;
        String lastname = PreferenceStore.getInstance(this).getString(PreferenceKeys.KEY_USERNAME, "");
        if(lastname.length() > 1){ //检测是否第一次登录
            isFirst = false;
        }
    	if(mCheckBox.isChecked()){ //检测是否离线登录
    		if(isFirst){ //第一次不能使用离线登录
    			Actions.toastShort(this, getString(R.string.login_fail_firstoffline));
    			return;
    		}else if(isNewUser){ //离线登录不能切换帐号
    			Actions.toastShort(this, getString(R.string.login_fail_changeusername));
    			return;
    		}else{ //离线登录
    			DataUtils.mUserData = new UserData();
    			DataUtils.mUserData.mRealName = 
    					PreferenceStore.getInstance(UserLoginActivity.this).getString(PreferenceKeys.KEY_REALNAME, "");
    			DataUtils.mUserData.mCounterName = 
    					PreferenceStore.getInstance(UserLoginActivity.this).getString(PreferenceKeys.KEY_STORENAME, "");
    			DataUtils.mUserData.mRoleType = 
    					PreferenceStore.getInstance(UserLoginActivity.this).getInt(PreferenceKeys.KEY_ROLETYPE, UserData.USERTYPE_SALESPERSON);
    			DataUtils.mUserData.mCounterTarget = 
    					PreferenceStore.getInstance(UserLoginActivity.this).getInt(PreferenceKeys.KEY_STORETARGET, -1);
    			 DataUtils.mUserData.isOffline = true;
                 DataUtils.mUserData.isNewUser = isNewUser;
                 DataUtils.mUserData.isNeedUpdate = false;

                 HttpUtil.mModulus = null;
         		 HttpUtil.mPublicKey = null;

                 jump2MainActivity();
                 return;
    		}
    	}
    	//在线登录
        showDialog(LOGIN_DIALOG);
        if(!HttpUtil.isSecure){
        	 new HttpConnectionMethod(new NetworkCallback(){
                 public void callFinished(int status, Object result) {
                     // TODO Auto-generated method stub
                 	SyncModel.LoginResult loginresult = ParseNetworkData.parseLoginResult(result);
                 	doResult(status, loginresult, isNewUser);
                 }
              }
             ).callPost(HttpUtil.getLoginUrl(), HttpUtil.getPutLoginContent(UserLoginActivity.this, name, password));
        }else{
        	new HttpConnectionMethod(new NetworkCallback(){
                public void callFinished(int status, Object result) {
                    // TODO Auto-generated method stub
                	SyncModel.SecureResult secureResult = ParseNetworkData.parseSecureResult(result);
                	doSecureResult(secureResult, name, password, isNewUser);
                }
             }
            ).callPost(HttpUtil.getSecureUrl(), HttpUtil.getPutSecureContent(UserLoginActivity.this, name));
        }
    }

    /**
     * 安全结果返回
     * @param secureResult 安全结果
     * @param name 用户名  
     * @param password 密码
     * @param isNewUser 是否为新用户
     */
    private void doSecureResult(SyncModel.SecureResult secureResult, String name, String password, final boolean isNewUser){
    	if(secureResult != null &&  secureResult.Status == SyncModel.SUCCEED){
    		HttpUtil.mModulus = secureResult.Modulus;
    		HttpUtil.mPublicKey = secureResult.PublicKey;
    		HttpUtil.mDesKey = DesUtil.getRandomString();

    		password = RsaUtil.rsaEncrypt(HttpUtil.mPublicKey, HttpUtil.mModulus, Encoder.MD5Encode(password) + " " + HttpUtil.mDesKey);
    		new HttpConnectionMethod(new NetworkCallback(){
                public void callFinished(int status, Object result) {
                    // TODO Auto-generated method stub
                	SyncModel.LoginResult loginresult = ParseNetworkData.parseLoginResult(result);
                	doResult(status, loginresult, isNewUser);
                }
             }
            ).callPost(HttpUtil.getSecureLoginUrl(), HttpUtil.getPutLoginContent(UserLoginActivity.this, name, password));
    	}else{ //获取Secure结果失败
    		doResult(SyncModel.FAIL_DATA, null, isNewUser);
    		HttpUtil.mModulus = null;
    		HttpUtil.mPublicKey = null;
    		HttpUtil.mDesKey = null;
    	}
    }

    /**
     * 登录结果
     * @param status 状态
     * @param result 返回结果
     * @param isNewUser 是否为新用户
     */
    private void doResult(final int status, final SyncModel.LoginResult result, final boolean isNewUser) {
    	//检测是否是新用户登录
		if(isNewUser){//新用户则清空历史数据
		    clearLastUserData();
		}
		if(result != null && result.Data != null && result.Data.ClearCache == 1 && result.Data.RoleType == UserData.USERTYPE_SUPERVISOR){ //清空缓存数据
			clearCacheSupervisorData();
		}
        mHander.post(new Runnable() {
            public void run() {
                if (result == null || status == HttpConnectionMethod.STATUS_ERROR || result.Status == 0) { //登录失败
                	dismissDialog(LOGIN_DIALOG);
                        DialogUtil.getSimpleDialog(UserLoginActivity.this,
                         getString(R.string.notice_label),
                         getString(R.string.login_unknow_error), null).show();
                } else { //登录成功
                	//保存数据至本地
                    PreferenceStore.getInstance(UserLoginActivity.this).putString(
                                 PreferenceKeys.KEY_REMEBER, REMEBER);
                    PreferenceStore.getInstance(UserLoginActivity.this).putString(
                            PreferenceKeys.KEY_USERNAME,
                            usernameTxt.getText().toString().trim());
                    PreferenceStore.getInstance(UserLoginActivity.this).putString(
                            PreferenceKeys.KEY_PASSWORD,
                            passwordTxt.getText().toString().trim());
                    PreferenceStore.getInstance(UserLoginActivity.this).putString(
                            PreferenceKeys.KEY_ID, result.Data.Uuid);
                    PreferenceStore.getInstance(UserLoginActivity.this).putString(
                            PreferenceKeys.KEY_REALNAME, result.Data.RealName);
                    PreferenceStore.getInstance(UserLoginActivity.this).putInt(
                            PreferenceKeys.KEY_ROLETYPE, result.Data.RoleType);
                    PreferenceStore.getInstance(UserLoginActivity.this).putString(
                            PreferenceKeys.KEY_STORENAME, result.Data.CounterName);
                    PreferenceStore.getInstance(UserLoginActivity.this).putInt(
                            PreferenceKeys.KEY_STORETARGET, result.Data.CounterTarget);
                    DataUtils.mUserData = new UserData();
                    DataUtils.mUserData.copyFrom(result);
                    DataUtils.mUserData.isOffline = false;
                    DataUtils.mUserData.isNewUser = isNewUser;

                    if(DataUtils.mUserData.isAdmin()){ //管理员不处理
                    	dismissDialog(LOGIN_DIALOG);
                    	jump2MainActivity();
                    }else{
                    	startLoginSync();
                    }
                }
            }
        });
    }

    /**
     * 按键事件处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_MENU) { //MENU
            if(ipText.getVisibility() == View.VISIBLE){
                ipText.setVisibility(View.GONE);
            }else{
                ipText.setVisibility(View.VISIBLE);
            }
            return true;
        }else if (keyCode==KeyEvent.KEYCODE_BACK) { //返回
        	this.finish();
            return true;
        }
        return false;
    }

    /**
     * 清空之前用户所有数据
     */
    private void clearLastUserData(){
        com.zhu.storesmanager.utils.Log.d("clearLastUserData");
        //删除促销员所有数据
        SalesData.getInstance(this).clearAllData(); //清除销量数据
        getContentResolver().delete(StoresManagerSettings.SignInInfoColumns.CONTENT_URI_NO_NOTIFICATION, null, null); //清除签到数据
        getContentResolver().delete(StoresManagerSettings.ModelsColumns.CONTENT_URI_NO_NOTIFICATION, null, null); //清除型号数据
        getContentResolver().delete(StoresManagerSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION, null, null); //清除提醒数据
        getContentResolver().delete(StoresManagerSettings.SpecialTaskColumns.CONTENT_URI_NO_NOTIFICATION, null, null); //清除特殊任务数据
        getContentResolver().delete(StoresManagerSettings.ReportedSalesColumns.CONTENT_URI_NO_NOTIFICATION, null, null); //清除已上报销量数据
        PreferenceStore.getInstance(this).putLong(PreferenceKeys.KEY_LASTLONGINTIME, System.currentTimeMillis());
        getContentResolver().delete(StoresManagerSettings.SupervisorStoreBoothColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.SupervisorStoreCompeteColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.SupervisorStoreCompeteSelectedColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.SupervisorStorePOSMColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.SupervisorStoreSampleColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.SupervisorVisitTaskColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.SupervisorStoreSalesColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.DataDictionaryColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        getContentResolver().delete(StoresManagerSettings.DataProjectsColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
    }

    /**
     * 开始登录后同步
     */
    private void startLoginSync(){
    	if(mLoginSyncData == null){
    		mLoginSyncData = new RemindSyncData(this, mHandler);
    	}
    	mLoginSyncData.startSync();
    }

    /**
     * 同步状态消息处理
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
        	  switch (msg.what) {
        	  	case RemindSyncData.SYNC_FAILEDEND:
        	  		dismissDialog(LOGIN_DIALOG);
        	  		Actions.toastShort(UserLoginActivity.this, R.string.login_sync_error);
                	jump2MainActivity();
        		  break;
        	  	case RemindSyncData.SYNC_SUCCESSEND:
        	  		dismissDialog(LOGIN_DIALOG);
                	jump2MainActivity();
        	  		break;
        	  }
        }
    };

    /**
     * 清空督导缓存数据
     */
    private void clearCacheSupervisorData(){
    	SupervisorData.clearCacheData(this);
    }
}
